from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from platforms.models import *
from userapp.models import *
from werkzeug.security import check_password_hash, generate_password_hash
from django.conf import settings
import jwt
import time
from tools.jwt_decode import login
from business.models import *
from datetime import datetime
# Create your views here.

# 注册
class ZhuView(APIView):
    def post(self,request):
        # 获取前端数据
        username = request.data.get('username')
        password = request.data.get('password')

        if not all([username, password]):
            return Response({
                'code': 40000,
                'message': '获取的数据为空'
            })

        # 判断唯一性
        pal = PlaUserModel.objects.filter(c_name=username).first()
        if not pal:
            passwords = generate_password_hash(password)
            PlaUserModel.objects.create(c_name=username,password=passwords)
            return Response({
                'code':20000,
                'message':'注册成功'
            })

# 登入
class PlaUserView(APIView):
    def post(self,request):
        # 获取前端数据
        username = request.data.get('username')
        password = request.data.get('password')

        if not all([username,password]):
            return Response({
                'code':40000,
                'message':'获取的数据为空'
            })
        try:
            user = PlaUserModel.objects.get(c_name=username)
        except Exception as e:
            print('>>>>>>>>>',e)
            return Response({
                'code':40000,
                'message':'没有此用户'
            })

        if check_password_hash(user.password,password):
            token = jwt.encode({
                'uid': user.id,
                'username': user.c_name,
                'exp': time.time() + 720000
            }, key=settings.SECRET_KEY, algorithm='HS256')

            return Response({
                'code':20000,
                'message':'登入成功',
                'data':{
                    'token': token,
                    "character": '大佬',
                    'uid': user.id
                },

            })

        return Response({
            'code':40000,
            'message':'密码错误'
        })

class UserView(APIView):
    def get(self,request):
        # 接受前端token
        deng = request.query_params.get('token')
        key = settings.SECRET_KEY
        token = jwt.decode(deng, key=key, algorithms='HS256')
        print('token的', token)

        u_id = token.get("uid")
        print('dasdasd',u_id)

        try:
            user = PlaUserModel.objects.get(id=u_id)
        except Exception as e:
            print('>>>>>>>>>',e)
            return Response({
                'code':40000,
                'message':'获取失败'
            })

        return Response({
            'code':20000,
            'message':'获取成功',
            'data':{
                'roles': '超级用户',
                'name': user.c_name,
                'avatar': user.portrait,
            }

        })

# 退出登入
class LogoutView(APIView):
    def post(self,request):
        return Response({
            "code":20000,
            "message":"退出登录成功"
        })

# 获取所有商家
class UserAllView(APIView):
    def get(self,request):

        bus = BusUserModel.objects.filter(delete=False)
        bus_list = []
        for i in bus:
            bus_list.append({
                'id':i.id,
                'username':i.b_name,
                'nickname':i.nickname,
                'portrait':i.portrait,
                'gender':i.gender,
                'mobile':i.mobile,
                'person':i.person,
                'business_time':i.business_time,
                'member':i.member,
                'freeze':i.freeze,
                'establish_time':datetime.strftime(i.establish_time,'%Y-%m-%d %H:%M:%S'),
                'change_time':i.change_time,
                'delete':i.delete,
            })
        return Response({
            'code':20000,
            'message':'获取成功',
            'data':bus_list
        })

    def post(self,request):
        # 获取前端数据
        username = request.data.get('username')
        password = request.data.get('password')
        mobile = request.data.get('mobile')
        person = request.data.get('person')
        gender = request.data.get('gender')
        portrait = request.data.get('portrait')

        if not all([username,password,mobile,person,gender,portrait]):
            return Response({
                'code':40000,
                'message':'获取数据为空'
            })

        user = BusUserModel.objects.filter(b_name=username).first()
        if user:
            return Response({
                'code': 40000,
                'message': '用户名不可重复'
            })

        users = BusUserModel.objects.filter(mobile=mobile).first()

        if users:
            return Response({
                'code': 40000,
                'message': '手机号不可重复'
            })
        # 密码加密
        password = generate_password_hash(password)

        BusUserModel.objects.create(
            b_name=username,
            password=password,
            mobile=mobile,
            person=person,
            gender=gender,
            portrait=portrait,
        )

        return Response({
            'code': 20000,
            'message': '添加成功'
        })

    def put(self,request):
        # 接受前端数据
        id = request.data.get('id')
        username = request.data.get('username')
        password = request.data.get('password')
        mobile = request.data.get('mobile')
        person = request.data.get('person')
        gender = request.data.get('gender')
        portrait = request.data.get('portrait')

        if not all([id,username,mobile,person,gender,portrait]):
            return Response({
                'code':40000,
                'message':'获取数据为空'
            })
        try:
            bus_user = BusUserModel.objects.get(id=id)
        except Exception as e:
            return Response({
                'code':40000,
                'message':'获取数据为空'
            })

        bus_user.b_name = username
        if password:
            password = generate_password_hash(password)
            bus_user.password = password

        bus_user.mobile = mobile
        bus_user.person = person
        bus_user.gender = gender
        bus_user.portrait = portrait
        bus_user.save()

        return Response({
            'code':20000,
            'message':'修改成功'
        })

    def delete(self,request):
        # 获取前端数据
        id = request.query_params.get('id')

        try:
            bus_user = BusUserModel.objects.get(id=id)
        except Exception as e:
            return Response({
                'code':40000,
                'message':'获取数据为空'
            })

        bus_user.delete = True
        bus_user.save()

        return Response({
            'code':20000,
            'message':'删除成功'
        })


# 获取单个商家信息
class UserInfoView(APIView):
    def get(self,request,id):
        try:
            bus = BusUserModel.objects.get(id=id)
        except Exception as e:
            return Response({
                'code':40000,
                'message':'获取失败'
            })

        return Response({
            'code':20000,
            'message':'获取成功',
            'data':{
                'id': bus.id,
                'username': bus.b_name,
                'nickname': bus.nickname,
                'portrait': bus.portrait,
                'gender': bus.gender,
                'mobile': bus.mobile,
                'person': bus.person,
                'business_time': bus.business_time,
                'member': bus.member,
                'freeze': bus.freeze,
                'establish_time': bus.establish_time,
                'change_time': bus.change_time,
                'delete': bus.delete,
            }
        })

    def put(self,request,id):
        # 获取前端数据
        vel = request.data.get('vel')

        try:
            bus = BusUserModel.objects.get(id=id)
        except Exception as e:
            return Response({
                'code':40000,
                'message':'获取失败'
            })

        bus.freeze = int(vel)
        bus.save()

        return Response({
            'code':20000,
            'message':'恢复正常' if vel == 2 else '已冻结'
        })


# 获取客户的信息
class CusUserView(APIView):
    def get(self,request):
        cus_user = CusUserModel.objects.filter(delete=False)
        cus_user_list = []
        for i in cus_user:
            cus_user_list.append({
                'id':i.id,
                'username':i.c_name,
                'nickname':i.nickname,
                'portrait':i.portrait,
                'gender':i.gender,
                'mobile':i.mobile,
                'member':i.member,
                'freeze':i.freeze,
                'establish_time':datetime.strftime(i.establish_time,'%Y-%m-%d %H:%M:%S'),
                'change_time':i.change_time,
                'delete':i.delete,
            })

        return Response({
            'code':20000,
            'message':'获取成功',
            'data':cus_user_list
        })


    def post(self,request):
        # 获取前端数据
        username = request.data.get('username')
        password = request.data.get('password')
        mobile = request.data.get('mobile')
        member = request.data.get('member')
        gender = request.data.get('gender')
        portrait = request.data.get('portrait')
        print('>>>>>>',username, password, mobile, gender, member, portrait)

        if not all([username, password, mobile, gender, member, portrait]):
            return Response({
                'code': 40000,
                'message': '获取数据为空'
            })

        user = CusUserModel.objects.filter(c_name=username).first()
        if user:
            return Response({
                'code': 40000,
                'message': '用户名不可重复'
            })

        users = CusUserModel.objects.filter(mobile=mobile).first()

        if users:
            return Response({
                'code': 40000,
                'message': '手机号不可重复'
            })
        # 密码加密
        password = generate_password_hash(password)

        CusUserModel.objects.create(
            c_name=username,
            password=password,
            mobile=mobile,
            gender=gender,
            member=member,
            portrait=portrait,
        )

        return Response({
            'code': 20000,
            'message': '添加成功'
        })






